/**
 * @file ai_glass_callback.c
 * @brief AI Glass回调接口框架实现
 * @author [Your Name]
 * @date 2025-09-28
 * @version 1.0
 * @copyright Copyright (c) 2025
 */

#include "ai_glass_callback.h"
#include "ai_glass_log.h"
#include <pthread.h>
#include <string.h>
#include <sys/time.h>
#include <errno.h>

/* ==================== 私有数据结构 ==================== */

/**
 * @brief 回调框架管理结构体
 */
typedef struct {
    ai_glass_callback_node_t*   callback_list;     // 回调函数链表
    pthread_mutex_t             mutex;             // 互斥锁
    int                         initialized;       // 初始化标志
    uint32_t                    next_task_id;      // 下一个任务ID
} ai_glass_callback_manager_t;

/* ==================== 全局变量 ==================== */

static ai_glass_callback_manager_t g_callback_manager = {
    .callback_list = NULL,
    .mutex = PTHREAD_MUTEX_INITIALIZER,
    .initialized = 0,
    .next_task_id = 1
};

/* ==================== 错误码描述表 ==================== */

static const char* error_strings[] = {
    [AI_GLASS_ERR_SUCCESS]              = "操作成功",
    [AI_GLASS_ERR_INIT_FAILED]          = "初始化失败",
    [AI_GLASS_ERR_MEMORY_ALLOC]         = "内存分配失败",
    [AI_GLASS_ERR_INVALID_PARAM]        = "无效参数",
    [AI_GLASS_ERR_NULL_POINTER]         = "空指针错误",
    [AI_GLASS_ERR_TIMEOUT]              = "操作超时",
    [AI_GLASS_ERR_BUSY]                 = "系统忙碌",
    [AI_GLASS_ERR_NOT_INITIALIZED]      = "未初始化",
    [AI_GLASS_ERR_ALREADY_RUNNING]      = "已在运行",
    [AI_GLASS_ERR_NOT_RUNNING]          = "未在运行",
    [AI_GLASS_ERR_IPI_DEVICE_OPEN]      = "IPI设备打开失败",
    [AI_GLASS_ERR_IPI_IOCTL_FAILED]     = "ioctl调用失败",
    [AI_GLASS_ERR_IPI_CMD_INVALID]      = "无效IPI命令",
    [AI_GLASS_ERR_IPI_RESPONSE_TIMEOUT] = "IPI响应超时",
    [AI_GLASS_ERR_IPI_MMAP_FAILED]      = "共享内存映射失败",
    [AI_GLASS_ERR_IPI_DATA_TOO_LARGE]   = "数据过大",
    [AI_GLASS_ERR_FILE_OPEN_FAILED]     = "文件打开失败",
    [AI_GLASS_ERR_FILE_READ_FAILED]     = "文件读取失败",
    [AI_GLASS_ERR_FILE_WRITE_FAILED]    = "文件写入失败",
    [AI_GLASS_ERR_FILE_SEEK_FAILED]     = "文件定位失败",
    [AI_GLASS_ERR_FILE_CLOSE_FAILED]    = "文件关闭失败",
    [AI_GLASS_ERR_FILE_NOT_EXIST]       = "文件不存在",
    [AI_GLASS_ERR_FILE_PERMISSION]      = "文件权限错误",
    [AI_GLASS_ERR_DISK_FULL]            = "磁盘空间不足",
    [AI_GLASS_ERR_CAMERA_INIT_FAILED]   = "相机初始化失败",
    [AI_GLASS_ERR_CAMERA_NOT_READY]     = "相机未就绪",
    [AI_GLASS_ERR_CAPTURE_FAILED]       = "拍照失败",
    [AI_GLASS_ERR_STORAGE_FULL]         = "存储空间不足",
    [AI_GLASS_ERR_FORMAT_NOT_SUPPORT]   = "格式不支持",
    [AI_GLASS_ERR_RECORD_INIT_FAILED]   = "录像初始化失败",
    [AI_GLASS_ERR_RECORD_START_FAILED]  = "录像开始失败",
    [AI_GLASS_ERR_RECORD_STOP_FAILED]   = "录像停止失败",
    [AI_GLASS_ERR_RECORD_TIME_TOO_SHORT] = "录像时间过短",
    [AI_GLASS_ERR_ENCODER_ERROR]        = "编码器错误",
    [AI_GLASS_ERR_AUDIO_INIT_FAILED]    = "音频初始化失败",
    [AI_GLASS_ERR_AUDIO_DEVICE_BUSY]    = "音频设备忙碌",
    [AI_GLASS_ERR_AUDIO_FORMAT_ERROR]   = "音频格式错误",
    [AI_GLASS_ERR_AUDIO_RECORD_FAILED]  = "音频录制失败",
    [AI_GLASS_ERR_RTSP_INIT_FAILED]     = "RTSP初始化失败",
    [AI_GLASS_ERR_RTSP_START_FAILED]    = "RTSP启动失败",
    [AI_GLASS_ERR_RTSP_STOP_FAILED]     = "RTSP停止失败",
    [AI_GLASS_ERR_NETWORK_CONNECT]      = "网络连接失败",
    [AI_GLASS_ERR_WIFI_CONNECT]         = "WiFi连接失败",
    [AI_GLASS_ERR_FTP_ERROR]            = "FTP错误",
    [AI_GLASS_ERR_UNKNOWN]              = "未知错误"
};

/* ==================== 状态描述表 ==================== */

static const char* state_strings[] = {
    [AI_GLASS_STATE_IDLE]           = "空闲",
    [AI_GLASS_STATE_INITIALIZING]   = "初始化中",
    [AI_GLASS_STATE_READY]          = "就绪",
    [AI_GLASS_STATE_RUNNING]        = "运行中",
    [AI_GLASS_STATE_PAUSED]         = "暂停",
    [AI_GLASS_STATE_STOPPING]       = "停止中",
    [AI_GLASS_STATE_ERROR]          = "错误",
    [AI_GLASS_STATE_COMPLETED]      = "完成"
};

/* ==================== 模块名称表 ==================== */

static const char* module_strings[] = {
    [AI_GLASS_MODULE_SYSTEM]    = "系统",
    [AI_GLASS_MODULE_IPI]       = "IPI通信",
    [AI_GLASS_MODULE_CAMERA]    = "相机",
    [AI_GLASS_MODULE_RECORD]    = "录像",
    [AI_GLASS_MODULE_AUDIO]     = "音频",
    [AI_GLASS_MODULE_RTSP]      = "RTSP",
    [AI_GLASS_MODULE_FILE]      = "文件系统",
    [AI_GLASS_MODULE_NETWORK]   = "网络"
};

/* ==================== 私有函数 ==================== */

/**
 * @brief 获取当前时间戳(毫秒)
 * @return 时间戳
 */
static uint64_t get_current_timestamp(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (uint64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

/**
 * @brief 检查回调是否匹配过滤条件
 * @param node 回调节点
 * @param info 回调信息
 * @return 1匹配，0不匹配
 */
static int is_callback_match(const ai_glass_callback_node_t* node, const ai_glass_callback_info_t* info)
{
    // 检查模块类型
    if (node->module != info->module) {
        return 0;
    }
    
    // 检查命令掩码
    if (node->cmd_mask != 0 && !(node->cmd_mask & (1 << info->cmd))) {
        return 0;
    }
    
    // 检查状态掩码
    if (node->state_mask != 0 && !(node->state_mask & (1 << info->state))) {
        return 0;
    }
    
    return 1;
}

/* ==================== 公共函数实现 ==================== */

/**
 * @brief 初始化回调框架
 */
int ai_glass_callback_init(void)
{
    pthread_mutex_lock(&g_callback_manager.mutex);
    
    if (g_callback_manager.initialized) {
        pthread_mutex_unlock(&g_callback_manager.mutex);
        ai_glass_log_warn("回调框架已经初始化");
        return 0;
    }
    
    g_callback_manager.callback_list = NULL;
    g_callback_manager.next_task_id = 1;
    g_callback_manager.initialized = 1;
    
    pthread_mutex_unlock(&g_callback_manager.mutex);
    
    ai_glass_log_info("回调框架初始化完成");
    return 0;
}

/**
 * @brief 销毁回调框架
 */
int ai_glass_callback_destroy(void)
{
    pthread_mutex_lock(&g_callback_manager.mutex);
    
    if (!g_callback_manager.initialized) {
        pthread_mutex_unlock(&g_callback_manager.mutex);
        ai_glass_log_warn("回调框架未初始化");
        return 0;
    }
    
    // 清理所有回调节点
    ai_glass_callback_node_t* current = g_callback_manager.callback_list;
    while (current) {
        ai_glass_callback_node_t* next = current->next;
        free(current);
        current = next;
    }
    
    g_callback_manager.callback_list = NULL;
    g_callback_manager.initialized = 0;
    
    pthread_mutex_unlock(&g_callback_manager.mutex);
    
    ai_glass_log_info("回调框架销毁完成");
    return 0;
}

/**
 * @brief 注册回调函数
 */
ai_glass_callback_node_t* ai_glass_callback_register(
    ai_glass_module_t module,
    uint32_t cmd_mask,
    ai_glass_state_t state_mask,
    ai_glass_callback_func_t callback,
    void* user_data)
{
    if (!callback) {
        ai_glass_log_error("回调函数指针为空");
        return NULL;
    }
    
    if (module >= AI_GLASS_MODULE_MAX) {
        ai_glass_log_error("无效的模块类型: %d", module);
        return NULL;
    }
    
    pthread_mutex_lock(&g_callback_manager.mutex);
    
    if (!g_callback_manager.initialized) {
        pthread_mutex_unlock(&g_callback_manager.mutex);
        ai_glass_log_error("回调框架未初始化");
        return NULL;
    }
    
    // 分配新节点
    ai_glass_callback_node_t* node = (ai_glass_callback_node_t*)malloc(sizeof(ai_glass_callback_node_t));
    if (!node) {
        pthread_mutex_unlock(&g_callback_manager.mutex);
        ai_glass_log_error("内存分配失败");
        return NULL;
    }
    
    // 初始化节点
    node->module = module;
    node->cmd_mask = cmd_mask;
    node->state_mask = state_mask;
    node->callback = callback;
    node->user_data = user_data;
    
    // 插入链表头部
    node->next = g_callback_manager.callback_list;
    g_callback_manager.callback_list = node;
    
    pthread_mutex_unlock(&g_callback_manager.mutex);
    
    ai_glass_log_info("注册回调成功: 模块=%s, 命令掩码=0x%x, 状态掩码=0x%x", 
                     ai_glass_get_module_string(module), cmd_mask, state_mask);
    
    return node;
}

/**
 * @brief 注销回调函数
 */
int ai_glass_callback_unregister(ai_glass_callback_node_t* handle)
{
    if (!handle) {
        ai_glass_log_error("回调句柄为空");
        return -1;
    }
    
    pthread_mutex_lock(&g_callback_manager.mutex);
    
    if (!g_callback_manager.initialized) {
        pthread_mutex_unlock(&g_callback_manager.mutex);
        ai_glass_log_error("回调框架未初始化");
        return -1;
    }
    
    // 在链表中查找并删除节点
    ai_glass_callback_node_t** current = &g_callback_manager.callback_list;
    while (*current) {
        if (*current == handle) {
            *current = handle->next;
            free(handle);
            pthread_mutex_unlock(&g_callback_manager.mutex);
            ai_glass_log_info("注销回调成功");
            return 0;
        }
        current = &(*current)->next;
    }
    
    pthread_mutex_unlock(&g_callback_manager.mutex);
    ai_glass_log_error("回调句柄无效");
    return -1;
}

/**
 * @brief 发送回调通知
 */
int ai_glass_callback_notify(const ai_glass_callback_info_t* info)
{
    if (!info) {
        ai_glass_log_error("回调信息为空");
        return -1;
    }
    
    pthread_mutex_lock(&g_callback_manager.mutex);
    
    if (!g_callback_manager.initialized) {
        pthread_mutex_unlock(&g_callback_manager.mutex);
        ai_glass_log_error("回调框架未初始化");
        return -1;
    }
    
    int callback_count = 0;
    
    // 遍历回调列表，调用匹配的回调函数
    ai_glass_callback_node_t* current = g_callback_manager.callback_list;
    while (current) {
        if (is_callback_match(current, info)) {
            // 释放锁后调用回调函数，避免死锁
            pthread_mutex_unlock(&g_callback_manager.mutex);
            
            try {
                current->callback(info, current->user_data);
                callback_count++;
            } catch (...) {
                ai_glass_log_error("回调函数执行异常");
            }
            
            // 重新获取锁继续遍历
            pthread_mutex_lock(&g_callback_manager.mutex);
        }
        current = current->next;
    }
    
    pthread_mutex_unlock(&g_callback_manager.mutex);
    
    ai_glass_log_debug("回调通知完成: 任务ID=%u, 模块=%s, 命令=0x%x, 状态=%s, 错误码=0x%x, 回调数量=%d",
                      info->task_id, ai_glass_get_module_string(info->module), 
                      info->cmd, ai_glass_get_state_string(info->state),
                      info->error_code, callback_count);
    
    return 0;
}

/**
 * @brief 创建回调信息结构体
 */
ai_glass_callback_info_t* ai_glass_callback_create_info(
    uint32_t task_id,
    ai_glass_module_t module,
    uint32_t cmd,
    ai_glass_state_t state,
    ai_glass_error_code_t error_code,
    uint32_t progress,
    const char* message)
{
    ai_glass_callback_info_t* info = (ai_glass_callback_info_t*)malloc(sizeof(ai_glass_callback_info_t));
    if (!info) {
        ai_glass_log_error("内存分配失败");
        return NULL;
    }
    
    memset(info, 0, sizeof(ai_glass_callback_info_t));
    
    info->task_id = task_id;
    info->module = module;
    info->cmd = cmd;
    info->state = state;
    info->error_code = error_code;
    info->timestamp = get_current_timestamp();
    info->progress = (progress > 100) ? 100 : progress;
    info->data_len = 0;
    info->data = NULL;
    
    if (message) {
        strncpy(info->message, message, sizeof(info->message) - 1);
        info->message[sizeof(info->message) - 1] = '\0';
    }
    
    return info;
}

/**
 * @brief 销毁回调信息结构体
 */
void ai_glass_callback_destroy_info(ai_glass_callback_info_t* info)
{
    if (info) {
        if (info->data) {
            free(info->data);
        }
        free(info);
    }
}

/**
 * @brief 获取错误码描述字符串
 */
const char* ai_glass_get_error_string(ai_glass_error_code_t error_code)
{
    // 系统级错误
    if (error_code >= AI_GLASS_ERR_SYSTEM_BASE && error_code < AI_GLASS_ERR_IPI_BASE) {
        int index = error_code - AI_GLASS_ERR_SYSTEM_BASE;
        if (index < sizeof(error_strings)/sizeof(error_strings[0])) {
            return error_strings[index + 1]; // +1 跳过SUCCESS
        }
    }
    // IPI错误
    else if (error_code >= AI_GLASS_ERR_IPI_BASE && error_code < AI_GLASS_ERR_FILE_BASE) {
        int index = error_code - AI_GLASS_ERR_IPI_BASE;
        return error_strings[10 + index]; // 偏移到IPI错误开始位置
    }
    // 文件错误
    else if (error_code >= AI_GLASS_ERR_FILE_BASE && error_code < AI_GLASS_ERR_CAMERA_BASE) {
        int index = error_code - AI_GLASS_ERR_FILE_BASE;
        return error_strings[16 + index]; // 偏移到文件错误开始位置
    }
    // 相机错误
    else if (error_code >= AI_GLASS_ERR_CAMERA_BASE && error_code < AI_GLASS_ERR_RECORD_BASE) {
        int index = error_code - AI_GLASS_ERR_CAMERA_BASE;
        return error_strings[25 + index]; // 偏移到相机错误开始位置
    }
    // 录像错误
    else if (error_code >= AI_GLASS_ERR_RECORD_BASE && error_code < AI_GLASS_ERR_AUDIO_BASE) {
        int index = error_code - AI_GLASS_ERR_RECORD_BASE;
        return error_strings[30 + index]; // 偏移到录像错误开始位置
    }
    // 音频错误
    else if (error_code >= AI_GLASS_ERR_AUDIO_BASE && error_code < AI_GLASS_ERR_NETWORK_BASE) {
        int index = error_code - AI_GLASS_ERR_AUDIO_BASE;
        return error_strings[35 + index]; // 偏移到音频错误开始位置
    }
    // 网络错误
    else if (error_code >= AI_GLASS_ERR_NETWORK_BASE && error_code < AI_GLASS_ERR_UNKNOWN) {
        int index = error_code - AI_GLASS_ERR_NETWORK_BASE;
        return error_strings[39 + index]; // 偏移到网络错误开始位置
    }
    // 成功状态
    else if (error_code == AI_GLASS_ERR_SUCCESS) {
        return error_strings[0];
    }
    
    return error_strings[sizeof(error_strings)/sizeof(error_strings[0]) - 1]; // 返回"未知错误"
}

/**
 * @brief 获取状态描述字符串
 */
const char* ai_glass_get_state_string(ai_glass_state_t state)
{
    if (state < sizeof(state_strings)/sizeof(state_strings[0])) {
        return state_strings[state];
    }
    return "未知状态";
}

/**
 * @brief 获取模块名称字符串
 */
const char* ai_glass_get_module_string(ai_glass_module_t module)
{
    if (module < sizeof(module_strings)/sizeof(module_strings[0])) {
        return module_strings[module];
    }
    return "未知模块";
}

/* ==================== 扩展功能函数 ==================== */

/**
 * @brief 生成新的任务ID
 * @return 任务ID
 */
uint32_t ai_glass_callback_generate_task_id(void)
{
    pthread_mutex_lock(&g_callback_manager.mutex);
    uint32_t task_id = g_callback_manager.next_task_id++;
    if (g_callback_manager.next_task_id == 0) {
        g_callback_manager.next_task_id = 1; // 避免使用0作为任务ID
    }
    pthread_mutex_unlock(&g_callback_manager.mutex);
    return task_id;
}

/**
 * @brief 设置回调信息的附加数据
 * @param info 回调信息结构体
 * @param data 数据指针
 * @param data_len 数据长度
 * @return 0成功，其他值失败
 */
int ai_glass_callback_set_data(ai_glass_callback_info_t* info, const void* data, uint32_t data_len)
{
    if (!info) {
        return -1;
    }
    
    // 释放旧数据
    if (info->data) {
        free(info->data);
        info->data = NULL;
        info->data_len = 0;
    }
    
    // 设置新数据
    if (data && data_len > 0) {
        info->data = malloc(data_len);
        if (!info->data) {
            ai_glass_log_error("内存分配失败");
            return -1;
        }
        memcpy(info->data, data, data_len);
        info->data_len = data_len;
    }
    
    return 0;
}